package com.ruoyi.web.controller.manage;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.system.domain.vo.*;
import com.ruoyi.system.service.CategoryService;
import com.ruoyi.system.service.ComingOutService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api")
public class ManageController {
    @Autowired
    private CategoryService categoryService;
    @PostMapping("/inventory/operations")
    public Result<Void> handleOperation(@RequestBody OperationVO vo) {
        categoryService.handleOperation(vo);
        return Result.success();
    }

    @PostMapping("/comingOutLog")
    public Result<Page<ComingOutVO>> comingOutLog(@RequestBody ComingOutLogRequest request) {
        return Result.success(categoryService.comingOutLog(request));
    }
    @PostMapping("/exportComingOutLog")
    public void exportComingOutLog(
            @RequestParam(value = "categoryId", required = false) Long categoryId,
            @RequestParam(value = "startTime", required = false) String startTime,
            @RequestParam(value = "endTime", required = false) String endTime,
            HttpServletResponse response) {
        ComingOutLogQueryParam params = new ComingOutLogQueryParam();
        params.setCategoryId(categoryId);
        params.setStartTime(startTime);
        params.setEndTime(endTime);
        try {
            List<ComingOutVO> logs = categoryService.getComingOutLogForExport(params);
            List<ComingOutLogExportDTO> exportData = logs.stream().map(log -> {
                ComingOutLogExportDTO dto = new ComingOutLogExportDTO();
                BeanUtils.copyProperties(log, dto);

                // 转换操作类型为中文
                dto.setOperationTypeStr(log.getOperationType() == 1 ? "入库" : "出库");

                return dto;
            }).collect(Collectors.toList());

            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("出入库记录", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            // 使用EasyExcel导出，指定DTO类
            EasyExcel.write(response.getOutputStream(), ComingOutLogExportDTO.class)
                    .sheet("出入库记录")
                    .doWrite(exportData);
        } catch (IOException e) {
            throw new RuntimeException("导出失败", e);
        }
    }
}
